package dtime

import (
	"fmt"
	"time"
)

type GptDtime struct {
	t   time.Time
	loc *time.Location
}

func NewGptTimeUtc() *GptDtime {
	g := GptDtime{t: time.Now()}
	err := g.SetTime(g.t, "UTC")
	if err != nil {
		return nil
	}
	return &g
}
func (d *GptDtime) SetTime(t time.Time, loc string) error {
	location, err := time.LoadLocation(loc)
	if err != nil {
		return fmt.Errorf("invalid timezone: %v", err)
	}
	d.t = t.In(location)
	d.loc = location
	return nil
}

// 获取指定格式的时间
func (d GptDtime) GetFormattedTime(format string) string {
	return d.t.Format(format)
}

// DateOnly formats
var dateFormats = map[string]string{
	"ymd":   "2006-01-02",
	"ymddm": "2006/01/02",
	"ymddy": "02 Jan 2006",
}

// DateTime formats
var dateTimeFormats = map[string]string{
	"ymd_hms":  "15:04:05",
	"ymdhms":   "2006-01-02 15:04:05",
	"iso8601":  "2006-01-02T15:04:05Z07:00",
	"unixtime": " unix timestamp", // returns Unix epoch time
}

func (d GptDtime) GetTimeYMD() string {
	return d.GetFormattedTime(dateFormats["ymd"])
}

func (d GptDtime) GetTimeYMDDiagonal() string {
	return d.GetFormattedTime(dateFormats["ymddm"])
}

func (d GptDtime) GetBeforeTimeYMD(years, months, days int) string {
	now := d.t.AddDate(-years, -months, -days)
	return now.Format(dateFormats["ymd"])
}

func (d GptDtime) GetAfterTimeYMD(years, months, days int) string {
	now := d.t.AddDate(years, months, days)
	return now.Format(dateFormats["ymd"])
}

// Additional time formats
func (d GptDtime) GetStringTime(t time.Time) string {
	return t.Format("2006-01-02")
}

func (d GptDtime) GetTimeYMDHMS() string {
	return d.GetFormattedTime(dateTimeFormats["ymdhms"])
}

// First day of month
func (d GptDtime) GetFirstDayOfMonth() string {
	firstDay := time.Date(d.t.Year(), d.t.Month(), 1, 0, 0, 0, 0, d.loc)
	return firstDay.Format(dateFormats["ymd"])
}
